import React, { useState, useEffect, useMemo } from "react";
import { SvgXml } from "react-native-svg";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  TouchableWithoutFeedback,
  ScrollView,
  StyleSheet,
  Animated,
  Dimensions,
  Platform,
  Keyboard,
  Alert,
} from "react-native";
import { Accelerometer } from "expo-sensors";
import authApi from "../../api/auth";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { router, useLocalSearchParams } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
const { width, height } = Dimensions.get("window");

export default function LoginScreen() {
  const { type } = useLocalSearchParams<{ type?: string }>();
  const mode = (typeof type === "string" ? type : "login") as
    | "login"
    | "register"
    | "forgot";
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [captcha, setCaptcha] = useState("");
  const [captchaData, setCaptchaData] = useState<{
    captchaId: string;
    captcha: string;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({
    username: "",
    password: "",
    captcha: "",
  });
  const [backgroundBubbleCount, setBackgroundBubbleCount] = useState(25); // 背景泡泡数量

  // 注册相关字段
  const [email, setEmail] = useState("");
  const [nickname, setNickname] = useState("");
  const [sex, setSex] = useState<string | undefined>(undefined); // "1" | "2" | "0"
  const [company, setCompany] = useState<string | undefined>(undefined);
  const [introduce, setIntroduce] = useState<string | undefined>(undefined);
  const [avatar, setAvatar] = useState<string | undefined>(undefined);
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showMore, setShowMore] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // 键盘动画值
  const keyboardOffset = new Animated.Value(0);

  // 动画值
  const backgroundX = new Animated.Value(0);
  const backgroundY = new Animated.Value(0);
  const formX = new Animated.Value(0);
  const formY = new Animated.Value(0);
  const logoScale = new Animated.Value(1);
  const logoRotate = new Animated.Value(0);

  useEffect(() => {
    // 键盘监听 - 流畅动画
    const keyboardWillShowListener = Keyboard.addListener(
      Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow",
      (event) => {
        const keyboardHeight =
          Platform.OS === "ios"
            ? event.endCoordinates.height
            : event.endCoordinates.height;

        Animated.timing(keyboardOffset, {
          toValue: -keyboardHeight * 0.3, // 只移动30%的键盘高度
          duration: Platform.OS === "ios" ? 300 : 250,
          useNativeDriver: true,
        }).start();
      }
    );

    const keyboardWillHideListener = Keyboard.addListener(
      Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide",
      () => {
        Animated.timing(keyboardOffset, {
          toValue: 0,
          duration: Platform.OS === "ios" ? 300 : 250,
          useNativeDriver: true,
        }).start();
      }
    );

    // 设置加速度计更新频率 - 提高帧率
    Accelerometer.setUpdateInterval(50);

    // 订阅加速度计数据
    const subscription = Accelerometer.addListener(({ x, y, z }) => {
      // 计算摇晃强度
      const shakeIntensity = Math.sqrt(x * x + y * y + z * z);

      // 计算动画值 - 增强效果
      const sensitivity = 80;
      const maxOffset = 60;

      // 背景动画 - 反向移动创造视差效果
      const bgX = Math.max(-maxOffset, Math.min(maxOffset, -x * sensitivity));
      const bgY = Math.max(-maxOffset, Math.min(maxOffset, y * sensitivity));

      // 表单动画 - 增强跟随效果
      const fX = Math.max(-25, Math.min(25, x * sensitivity * 0.4));
      const fY = Math.max(-25, Math.min(25, -y * sensitivity * 0.4));

      // Logo动画 - 增强效果
      const scale = 1 + Math.abs(z - 9.8) * 0.08;
      const rotate = x * 25;

      // 执行动画 - 高帧率流畅效果
      Animated.parallel([
        Animated.timing(backgroundX, {
          toValue: bgX,
          duration: 120,
          useNativeDriver: true,
        }),
        Animated.timing(backgroundY, {
          toValue: bgY,
          duration: 120,
          useNativeDriver: true,
        }),
        Animated.timing(formX, {
          toValue: fX,
          duration: 120,
          useNativeDriver: true,
        }),
        Animated.timing(formY, {
          toValue: fY,
          duration: 120,
          useNativeDriver: true,
        }),
        Animated.timing(logoScale, {
          toValue: scale,
          duration: 120,
          useNativeDriver: true,
        }),
        Animated.timing(logoRotate, {
          toValue: rotate,
          duration: 120,
          useNativeDriver: true,
        }),
      ]).start();
    });

    return () => {
      subscription?.remove();
      keyboardWillShowListener?.remove();
      keyboardWillHideListener?.remove();
    };
  }, []);

  const validateForm = (hasCaptcha?: boolean) => {
    const newErrors = { username: "", password: "", captcha: "" };

    if (!username.trim()) {
      newErrors.username = "请输入用户名或邮箱";
    }

    if (!password.trim()) {
      newErrors.password = "请输入密码";
    } else if (password.length < 6) {
      newErrors.password = "密码至少需要6位";
    }

    if (hasCaptcha && !captcha.trim()) {
      newErrors.captcha = "请输入验证码";
    }

    setErrors(newErrors);
    return !newErrors.username && !newErrors.password;
  };
  const getCaptcha = async () => {
    const { data } = await authApi.getCaptcha();
    console.log(data, "==getCaptcha");

    setCaptchaData(data);
  };
  const handleLogin = async () => {
    try {
      if (!validateForm()) {
        return;
      }
      setIsLoading(true);
      if (!captchaData) {
        await getCaptcha();
        setIsLoading(false);
        return;
      }
      setCaptchaData(null);
      if (!validateForm(true)) {
        return;
      }

      const { data } = await authApi.login({
        captchaId: captchaData?.captchaId,
        captchaText: captcha,
        username,
        email: username,
        password,
      });
      console.log(data, "====");
      setIsLoading(false);
      setCaptcha("");

      // 这里可以添加实际的登录API调用
      console.log("登录成功:", { username, password });
      // 存储Token到AsyncStorage
      await AsyncStorage.setItem("token", data);
      // 登录成功后的处理（比如导航到主页）
      router.back();
    } catch (error) {
      console.error("登录失败:", error);
      // 可以显示错误提示
    } finally {
      setIsLoading(false);
    }
  };

  const handleRegister = async () => {
    try {
      // 校验基础必填
      if (!username.trim()) {
        Alert.alert("提示", "请输入用户名");
        return;
      }
      if (!nickname.trim()) {
        Alert.alert("提示", "请输入昵称");
        return;
      }
      if (!email.trim()) {
        Alert.alert("提示", "请输入邮箱");
        return;
      }
      if (!password.trim() || password.length < 6) {
        Alert.alert("提示", "请输入不少于6位的密码");
        return;
      }
      if (!confirmPassword.trim()) {
        Alert.alert("提示", "请再次输入密码");
        return;
      }
      if (password !== confirmPassword) {
        Alert.alert("提示", "两次输入的密码不一致");
        return;
      }

      setIsLoading(true);
      if (!captchaData) {
        await getCaptcha();
        setIsLoading(false);
        return;
      }
      if (!captcha.trim()) {
        setIsLoading(false);
        Alert.alert("提示", "请输入验证码");
        return;
      }

      const { data } = await authApi.register({
        avatar,
        captchaId: captchaData.captchaId,
        captchaText: captcha,
        company,
        email,
        introduce,
        nickname,
        password,
        sex,
        username,
      });

      setCaptcha("");
      setCaptchaData(null);
      router.back();
    } catch (error) {
      console.error("注册失败:", error);
      Alert.alert("错误", (error as any)?.message || "注册失败");
      getCaptcha();
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgot = async () => {
    try {
      if (!email.trim()) {
        Alert.alert("提示", "请输入邮箱");
        return;
      }
      setIsLoading(true);
      if (!captchaData) {
        await getCaptcha();
        setIsLoading(false);
        return;
      }
      if (!captcha.trim()) {
        setIsLoading(false);
        Alert.alert("提示", "请输入验证码");
        return;
      }
      await authApi.forgotPassword({
        email,
        captchaId: captchaData.captchaId,
        captchaText: captcha,
      });
      Alert.alert("成功", "重置密码邮件已发送，如未收到请检查垃圾箱");
      setCaptcha("");
      setCaptchaData(null);
      router.back();
    } catch (error) {
      console.error("忘记密码提交失败:", error);
      Alert.alert("错误", (error as any)?.message || "提交失败");
    } finally {
      setIsLoading(false);
    }
  };

  // 生成背景泡泡数据（使用 useMemo 缓存，避免每次渲染都重新生成）
  const backgroundBubbleData = useMemo(() => {
    const bubbles = [];
    for (let i = 0; i < backgroundBubbleCount; i++) {
      const size = Math.random() * 80 + 30; // 30-110px
      const left = Math.random() * width;
      const top = Math.random() * height;
      const opacity = Math.random() * 0.4 + 0.2; // 0.2-0.6
      const scale = Math.random() * 0.3 + 0.8; // 0.8-1.1 随机缩放

      bubbles.push({
        key: `bg-${i}`,
        size,
        left,
        top,
        opacity,
        scale,
      });
    }
    return bubbles;
  }, [backgroundBubbleCount]);

  // 生成背景泡泡组件（在卡片后面）
  const renderBackgroundBubbles = () => {
    return backgroundBubbleData.map((bubble) => (
      <Animated.View
        key={bubble.key}
        style={[
          styles.backgroundBubble,
          {
            width: bubble.size,
            height: bubble.size,
            left: bubble.left,
            top: bubble.top,
            opacity: bubble.opacity,
            transform: [
              { translateX: backgroundX },
              { translateY: backgroundY },
              { scale: bubble.scale },
            ],
          },
        ]}
      />
    ));
  };

  // 处理点击外部区域失焦
  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <View style={styles.container}>
        {/* 背景泡泡层（在卡片后面） */}
        <View style={styles.backgroundLayer}>{renderBackgroundBubbles()}</View>

        {/* 主要内容 */}
        <Animated.View
          style={[
            styles.content,
            {
              transform: [{ translateY: keyboardOffset }],
            },
          ]}
        >
          {/* 标题区域 */}
          <View style={styles.titleContainer}>
            <Text style={styles.welcomeText}>
              {mode === "login" && "Welcome Back"}
              {mode === "forgot" && "Reset Password"}
            </Text>
            <Text style={styles.subtitleText}>
              {mode === "login" && "Sign in to continue"}
              {mode === "forgot" && "Receive reset instructions via email"}
            </Text>
          </View>

          {/* 表单 */}
          <Animated.View
            style={[
              styles.formContainer,
              {
                transform: [{ translateX: formX }, { translateY: formY }],
              },
              mode === "register" ? { marginTop: -150 } : null,
            ]}
          >
            {/* 用户名 / 邮箱（登录用合一输入）或注册时拆分 */}
            <View style={{ maxHeight: height * 0.55 }}>
              <ScrollView
                keyboardShouldPersistTaps="handled"
                showsVerticalScrollIndicator={false}
              >
                {mode === "login" && (
                  <>
                    <View style={styles.inputContainer}>
                      <TextInput
                        style={[
                          styles.input,
                          errors.username && styles.inputError,
                        ]}
                        placeholder="用户名/邮箱"
                        placeholderTextColor="#999"
                        value={username}
                        onChangeText={(text) => {
                          setUsername(text);
                          if (errors.username) {
                            setErrors((prev) => ({ ...prev, username: "" }));
                          }
                        }}
                      />
                      {errors.username ? (
                        <Text style={styles.errorText}>{errors.username}</Text>
                      ) : null}
                    </View>
                    <View style={styles.inputContainer}>
                      <View style={styles.inputWrapper}>
                        <TextInput
                          style={[
                            styles.input,
                            errors.password && styles.inputError,
                            { paddingRight: 48 },
                          ]}
                          placeholder="密码"
                          placeholderTextColor="#999"
                          secureTextEntry={!showPassword}
                          value={password}
                          onChangeText={(text) => {
                            setPassword(text);
                            if (errors.password) {
                              setErrors((prev) => ({ ...prev, password: "" }));
                            }
                          }}
                        />
                        <TouchableOpacity
                          style={styles.eyeButton}
                          onPress={() => setShowPassword((v) => !v)}
                        >
                          <Ionicons
                            name={showPassword ? "eye-off" : "eye"}
                            size={22}
                            color="#8A63D2"
                          />
                        </TouchableOpacity>
                      </View>
                      {errors.password ? (
                        <Text style={styles.errorText}>{errors.password}</Text>
                      ) : null}
                    </View>
                  </>
                )}

                {mode === "register" && (
                  <>
                    <View style={styles.inputContainer}>
                      <TextInput
                        style={[styles.input]}
                        placeholder="用户名*"
                        placeholderTextColor="#999"
                        value={username}
                        onChangeText={setUsername}
                      />
                    </View>
                    <View style={styles.inputContainer}>
                      <TextInput
                        style={[styles.input]}
                        placeholder="昵称*"
                        placeholderTextColor="#999"
                        value={nickname}
                        onChangeText={setNickname}
                      />
                    </View>
                    <View style={styles.inputContainer}>
                      <TextInput
                        style={[styles.input]}
                        placeholder="邮箱*"
                        placeholderTextColor="#999"
                        value={email}
                        onChangeText={setEmail}
                        keyboardType="email-address"
                      />
                    </View>
                    <View style={styles.inputContainer}>
                      <View style={styles.inputWrapper}>
                        <TextInput
                          style={[styles.input, { paddingRight: 48 }]}
                          placeholder="密码（至少6位）*"
                          placeholderTextColor="#999"
                          secureTextEntry={!showPassword}
                          value={password}
                          onChangeText={setPassword}
                        />
                        <TouchableOpacity
                          style={styles.eyeButton}
                          onPress={() => setShowPassword((v) => !v)}
                        >
                          <Ionicons
                            name={showPassword ? "eye-off" : "eye"}
                            size={22}
                            color="#8A63D2"
                          />
                        </TouchableOpacity>
                      </View>
                    </View>
                    <View style={styles.inputContainer}>
                      <View style={styles.inputWrapper}>
                        <TextInput
                          style={[styles.input, { paddingRight: 48 }]}
                          placeholder="确认密码*"
                          placeholderTextColor="#999"
                          secureTextEntry={!showConfirmPassword}
                          value={confirmPassword}
                          onChangeText={setConfirmPassword}
                        />
                        <TouchableOpacity
                          style={styles.eyeButton}
                          onPress={() => setShowConfirmPassword((v) => !v)}
                        >
                          <Ionicons
                            name={showConfirmPassword ? "eye-off" : "eye"}
                            size={22}
                            color="#8A63D2"
                          />
                        </TouchableOpacity>
                      </View>
                    </View>

                    <TouchableOpacity
                      onPress={() => setShowMore((v) => !v)}
                      style={{ alignSelf: "flex-start", marginBottom: 12 }}
                    >
                      <Text style={styles.footerText}>
                        {showMore ? "收起可选信息" : "更多信息（可选）"}
                      </Text>
                    </TouchableOpacity>

                    {showMore && (
                      <>
                        <View style={styles.inputContainer}>
                          <TextInput
                            style={[styles.input]}
                            placeholder="性别（1男 2女 0未知，可选）"
                            placeholderTextColor="#999"
                            value={sex}
                            onChangeText={setSex}
                          />
                        </View>
                        <View style={styles.inputContainer}>
                          <TextInput
                            style={[styles.input]}
                            placeholder="公司（可选）"
                            placeholderTextColor="#999"
                            value={company}
                            onChangeText={setCompany}
                          />
                        </View>
                        <View style={styles.inputContainer}>
                          <TextInput
                            style={[styles.input]}
                            placeholder="头像地址（可选）"
                            placeholderTextColor="#999"
                            value={avatar}
                            onChangeText={setAvatar}
                          />
                        </View>
                        <View style={styles.inputContainer}>
                          <TextInput
                            style={[styles.input]}
                            placeholder="个人介绍（可选）"
                            placeholderTextColor="#999"
                            value={introduce}
                            onChangeText={setIntroduce}
                          />
                        </View>
                      </>
                    )}
                  </>
                )}

                {mode === "forgot" && (
                  <>
                    <View style={styles.inputContainer}>
                      <TextInput
                        style={[styles.input]}
                        placeholder="邮箱"
                        placeholderTextColor="#999"
                        value={email}
                        onChangeText={setEmail}
                        keyboardType="email-address"
                      />
                    </View>
                  </>
                )}

                {captchaData && (
                  <TouchableOpacity onPress={getCaptcha}>
                    <SvgXml
                      onPress={getCaptcha}
                      style={styles.captchaImage}
                      xml={captchaData.captcha}
                    />
                  </TouchableOpacity>
                )}

                {captchaData && (
                  <View style={styles.inputContainer}>
                    <TextInput
                      style={[styles.input]}
                      placeholder="验证码"
                      placeholderTextColor="#999"
                      value={captcha}
                      onChangeText={(text) => {
                        setCaptcha(text);
                        if (errors.captcha) {
                          setErrors((prev) => ({ ...prev, captcha: "" }));
                        }
                      }}
                    />
                    {errors.captcha ? (
                      <Text style={styles.errorText}>{errors.captcha}</Text>
                    ) : null}
                  </View>
                )}
              </ScrollView>
            </View>

            <TouchableOpacity
              style={[
                styles.loginButton,
                isLoading && styles.loginButtonDisabled,
              ]}
              onPress={
                mode === "login"
                  ? handleLogin
                  : mode === "register"
                  ? handleRegister
                  : handleForgot
              }
              disabled={isLoading}
            >
              {isLoading ? (
                <View style={styles.loadingContainer}>
                  <Text style={styles.loginButtonText}>
                    {mode === "login" && "处理中..."}
                    {mode === "register" && "处理中..."}
                    {mode === "forgot" && "处理中..."}
                  </Text>
                </View>
              ) : (
                <Text style={styles.loginButtonText}>
                  {mode === "login" && "登录"}
                  {mode === "register" && "注册"}
                  {mode === "forgot" && "发送重置邮件"}
                </Text>
              )}
            </TouchableOpacity>

            <View style={styles.footer}>
              {mode !== "forgot" ? (
                <TouchableOpacity
                  onPress={() =>
                    router.replace({
                      pathname: "/auth/login",
                      params: { type: "forgot" },
                    })
                  }
                >
                  <Text style={styles.footerText}>忘记密码？</Text>
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  onPress={() =>
                    router.replace({
                      pathname: "/auth/login",
                      params: { type: "login" },
                    })
                  }
                >
                  <Text style={styles.footerText}>返回登录</Text>
                </TouchableOpacity>
              )}
              {mode !== "register" ? (
                <TouchableOpacity
                  onPress={() =>
                    router.replace({
                      pathname: "/auth/login",
                      params: { type: "register" },
                    })
                  }
                >
                  <Text style={styles.footerText}>注册账号</Text>
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  onPress={() =>
                    router.replace({
                      pathname: "/auth/login",
                      params: { type: "login" },
                    })
                  }
                >
                  <Text style={styles.footerText}>已有账号？去登录</Text>
                </TouchableOpacity>
              )}
            </View>
          </Animated.View>
        </Animated.View>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  captchaImage: {
    width: 100,
    height: 40,
  },
  container: {
    flex: 1,
    backgroundColor: "#ECE6FF",
  },
  backgroundLayer: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    overflow: "hidden",
    zIndex: 1,
  },
  foregroundLayer: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    overflow: "hidden",
    zIndex: 2, // 降低层级，让卡片能挡住泡泡
    pointerEvents: "none", // 确保不阻挡用户交互
  },
  backgroundBubble: {
    position: "absolute",
    backgroundColor: "#B19CD9",
    borderRadius: 50,
    shadowColor: "#B19CD9",
    shadowOffset: {
      width: 0,
      height: 3,
    },
    shadowOpacity: 0.4,
    shadowRadius: 6,
    elevation: 4,
  },
  bubble: {
    position: "absolute",
    backgroundColor: "#B19CD9",
    borderRadius: 50,
    shadowColor: "#B19CD9",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 3,
  },
  content: {
    flex: 1,
    justifyContent: "center",
    paddingHorizontal: 30,
    zIndex: 3, // 确保内容在泡泡之上
  },
  titleContainer: {
    alignItems: "center",
    marginBottom: 50,
  },
  welcomeText: {
    fontSize: 36,
    fontWeight: "700",
    color: "#FFFFFF",
    marginBottom: 12,
    letterSpacing: 1,
    textShadowColor: "rgba(0, 0, 0, 0.3)",
    textShadowOffset: { width: 0, height: 2 },
    textShadowRadius: 4,
  },
  subtitleText: {
    fontSize: 18,
    fontWeight: "300",
    color: "rgba(255, 255, 255, 0.9)",
    letterSpacing: 0.5,
    textShadowColor: "rgba(0, 0, 0, 0.2)",
    textShadowOffset: { width: 0, height: 1 },
    textShadowRadius: 2,
  },
  formContainer: {
    backgroundColor: "rgba(255, 255, 255, 0.98)", // 增加不透明度，更好地遮挡泡泡
    borderRadius: 20,
    padding: 30,
    shadowColor: "#8A63D2",
    shadowOffset: {
      width: 0,
      height: 15,
    },
    shadowOpacity: 0.15,
    shadowRadius: 25,
    elevation: 15,
    borderWidth: 1,
    borderColor: "rgba(138, 99, 210, 0.1)",
    zIndex: 4, // 确保表单容器在最上层
  },
  inputContainer: {
    marginBottom: 20,
  },
  input: {
    height: 44,
    borderWidth: 1,
    borderColor: "#E8E8E8",
    borderRadius: 25,
    paddingHorizontal: 20,
    fontSize: 16,
    backgroundColor: "#FFFFFF",
    color: "#2A2929",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  inputWrapper: {
    position: "relative",
    justifyContent: "center",
  },
  eyeButton: {
    position: "absolute",
    right: 12,
    height: 44,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 8,
  },
  eyeText: {
    color: "#8A63D2",
    fontSize: 14,
  },
  inputError: {
    borderColor: "#FF6B6B",
    borderWidth: 2,
  },
  errorText: {
    color: "#FF6B6B",
    fontSize: 12,
    marginTop: 5,
    marginLeft: 20,
  },
  loginButton: {
    height: 50,
    backgroundColor: "#8A63D2",
    borderRadius: 25,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 10,
    shadowColor: "#8A63D2",
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 8,
  },
  loginButtonText: {
    color: "white",
    fontSize: 18,
    fontWeight: "600",
  },
  loginButtonDisabled: {
    backgroundColor: "#A0A0A0",
    opacity: 0.7,
  },
  loadingContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  footer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginTop: 30,
  },
  footerText: {
    color: "#8A63D2",
    fontSize: 14,
  },
});
